package com.chixing.day11.Date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTest {
    public static void main(String[] args) throws ParseException {
        //1. 比较两个日期的先后顺序
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dat2 = formatter.parse("2015-01-01");
        Date dat3 = formatter.parse("2020-01-01");

        if (dat2.compareTo(dat3) > 0) {
            System.out.println("Date1 时间在 Date2 之后");
        } else if (dat2.compareTo(dat3) < 0) {
            System.out.println("Date1 时间在 Date2 之前");
        } else if (dat2.compareTo(dat3) == 0) {
            System.out.println("Date1 时间与 Date2 相等");
        } else {
            System.out.println("程序怎么会运行到这里?正常应该不会");
        }
        System.out.println("==================================");


        //2. 获得当前时间的年月日 时分秒
        Calendar now = Calendar.getInstance();
        System.out.println("年: " + now.get(Calendar.YEAR));
        System.out.println("月: " + (now.get(Calendar.MONTH) + 1) );
        System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
        System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
        System.out.println("分: " + now.get(Calendar.MINUTE));
        System.out.println("秒: " + now.get(Calendar.SECOND));
        System.out.println(now.getTime());
        System.out.println("==================================");


        //3. 将 字符串"2000-1-12" 转换成 日期对象
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        String da = "2000-01-12";
        Date da1 = sdf.parse(da);
        System.out.println(da1);


        //Date ---> String
         SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss:SSS  " );
         String dateStr = sdf2.format(new Date());
         System.out.println(dateStr);

        //String -->Date
        dateStr = "2022-08-01 16:59:20:300";
        SimpleDateFormat sdf3 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss:SSS  " );
        try{
            Date date3 = sdf3.parse(dateStr);
            System.out.println(date3);
        } catch(ParseException e){
            e.printStackTrace();
        }
    }
}

